<template>
  <div class="box">
    <el-row>
      <el-col :span="24">
        <div class="header">
          <el-form
            ref="form"
            :model="form"
            label-width="100px"
            class="flex-bottom"
          >
            <div class="flex">
              <el-form-item label="所属网点">
                <el-select
                  v-model="value"
                  placeholder="请选择所属网点"
                  style="width: 286px"
                  @change="lineChange"
                >
                  <el-option
                    v-for="item in newOptions"
                    :key="item.id"
                    :label="item.networkName"
                    :value="item.id"
                  />
                </el-select>
                <!-- <el-input v-model="form.name" placeholder="请输入网点名称" style="width: 286px" /> -->
              </el-form-item>
            </div>
            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button @click="resetBtn">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
    <el-row class="flex">
      <div class="left">
        <div class="left-tree">
          <el-tree
            ref="tree"
            :data="data"
            show-checkbox
            node-key="id"
            :check-strictly="true"
            :default-expand-all="false"
            :props="defaultProps"
            @node-click="handleNodeClick"
            @check-change="handleCheckChange"
          />
        </div>
      </div>
      <div class="left right">
        <div class="just-bet">
          <div>
            <el-button
              v-if="disabled == true"
              type="primary"
              @click="editOnline"
            >在线编辑</el-button>
            <el-button v-else @click="editCancle">取消编辑</el-button>
            <el-button
              v-if="disabled == false"
              type="primary"
              @click="saveTable"
            >保存</el-button>
          </div>
          <div>
            <!-- <el-button>资产折旧说明<i class="el-icon-warning-outline"></i></el-button> -->
            <el-button>同步上月金额</el-button>
            <el-button @click="addSubject">新增科目</el-button>
            <!-- <el-button>我的票据</el-button> -->
            <el-button><i class="el-icon-upload2" />导出</el-button>
          </div>
        </div>
        <!-- <el-table :data="tableData" border :span-method="objectSpanMethod" border style="width: 100%; margin-top: 20px"> -->
        <el-table
          :data="tableData"
          :span-method="objectSpanMethod"
          border
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column prop="name" label="一级科目">
            <template slot-scope="scope">
              {{ scope.row.feeSubject.name }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="二级科目">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column prop="thisMonthAmount" label="本月金额(元）">
            <template slot-scope="scope">
              <el-input-number
                v-model.trim="scope.row.thisMonthAmount"
                size="small"
                :min="0"
                :controls="false"
                :disabled="disabled"
              />
            </template>
          </el-table-column>
          <el-table-column prop="thisYearAmount" label="本年金额(元）" />
          <el-table-column prop="remark" label="备注">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.remark"
                size="small"
                placeholder="请输入备注内容"
                :disabled="disabled"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 新增科目弹窗 -->
      <el-dialog
        title="新增科目"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="20%"
        >
          <el-form-item label="一级科目" prop="subject">
            <el-select
              v-model="ruleForm.subject"
              placeholder="请选择一级科目"
              style="width: 60%"
              @change="selectChange"
            >
              <el-option
                v-for="item in levelOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="二级科目" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入二级科目"
              style="width: 60%"
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetForm(ruleForm)">取 消</el-button>
          <el-button type="primary" @click="save(ruleForm)">确 定</el-button>
        </span>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import {
  getNetworkInfo,
  addSubject,
  searchSubject,
  editSubject,
  selectMonth,
  selectOneLevel
} from '@/api/branchFinance/wages/fixed'
export default {
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 下拉框
      newOptions: [],
      levelOptions: [],
      value: '',
      form: {
        name: ''
      },
      ruleForm: {
        name: '',
        subject: ''
      },
      tableData: [],
      spanArr: [],
      position: 0,
      dialogVisible: false,
      rules: {
        name: [
          {
            required: true,
            message: '请输入二级科目',
            trigger: 'blur'
          }
        ],
        subject: [
          {
            required: true,
            message: '请选择一级科目',
            trigger: 'change'
          }
        ]
      },
      disabled: true,
      current: '',
      searchCurrent: '',
      dataId: ''
    }
  },
  mounted() {
    // this.init();
    this.getList()
    this.getMonth()
    this.getLevel()
  },
  methods: {
    // 所属网点下拉框
    getList() {
      getNetworkInfo().then((res) => {
        this.newOptions = res.data
      })
      // .catch((error) => {})
    },
    // 获取月份信息
    getMonth() {
      selectMonth().then((res) => {
        console.log(res, 'res月份信息')
        const array = []
        const arr = res.data
        arr.forEach((item, index) => {
          array.push({
            label: item.year + '年',
            children: item.month
          })
        })
        this.data = array
      })
      // .catch((error) => {})
    },
    // 获取一级科目下拉框
    getLevel() {
      selectOneLevel().then((res) => {
        // console.log(res, 'res')
        this.levelOptions = res.data
      })
      // .catch((error) => {})
    },
    // 表格合并
    init() {
      this.spanArr = []
      this.tableData.forEach((item, index) => {
        if (index === 0) {
          this.spanArr.push(1)
          this.position = 0
        } else {
          if (
            this.tableData[index].feeSubject.name ===
            this.tableData[index - 1].feeSubject.name
          ) {
            this.spanArr[this.position] += 1
            this.spanArr.push(0)
          } else {
            this.spanArr.push(1)
            this.position = index
          }
        }
      })
    },
    // 所属网点选中数据
    lineChange(e) {
      this.searchCurrent = e
    },
    // 搜索
    search() {
      if (this.searchCurrent === '') {
        this.$message.warning('请选择所属网点！')
        return false
      }
      if (this.dataId === '') {
        this.$message.warning('请选择月份！')
        return false
      }
      const params = {
        month: this.dataId,
        networkNameId: this.searchCurrent
      }
      searchSubject(params).then((res) => {
        const list = res.data
        const arr = []
        for (let i = 0; i < this.levelOptions.length; i++) {
          arr.push(this.levelOptions[i].name)
        }
        const cdList = []
        const clList = []
        const zcList = []
        const glList = []
        const qtList = []
        list.forEach((item, index) => {
          if (item.feeSubject.name === arr[0]) {
            cdList.push(item)
          } else if (item.feeSubject.name === arr[1]) {
            clList.push(item)
          } else if (item.feeSubject.name === arr[2]) {
            zcList.push(item)
          } else if (item.feeSubject.name === arr[3]) {
            glList.push(item)
          } else if (item.feeSubject.name === arr[4]) {
            qtList.push(item)
          }
        })
        this.tableData = cdList
          .concat(clList)
          .concat(zcList)
          .concat(glList)
          .concat(qtList)
        this.init()
      })
      // .catch((error) => {})
    },
    // 取消编辑
    editCancle() {
      this.disabled = true
    },
    // 在线编辑
    editOnline() {
      console.log(this.tableData, '---')
      if (this.tableData.length === 0) {
        this.$message.warning('请先查询表格数据！')
        return false
      } else {
        this.disabled = false
      }
    },
    // 在线编辑保存操作
    saveTable() {
      const params = this.tableData
      editSubject(params).then((res) => {
        console.log(res, '---')
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.editCancle()
          this.search()
        } else {
          this.$message.warning(res.msg)
        }
      })
      // .catch((error) => {})
    },
    // 新增
    addSubject() {
      if (this.searchCurrent === '') {
        console.log(this.dataId, 'this.dataId')
        this.$message.warning('请选择所属网点！')
        return false
      } else if (this.dataId === '') {
        this.$message.warning('请选择日期！')
        return false
      } else {
        this.dialogVisible = true
      }
      // this.dialogVisible = true;
    },
    // 保存
    save(ruleForm) {
      // console.log(ruleForm, 'ruleForm')
      this.$refs['ruleForm'].validate((valid) => {
        if (valid === true) {
          const label = this.dataId
          const params = {
            networkNameId: this.searchCurrent,
            parentId: this.current,
            name: ruleForm.name,
            label: label
          }
          addSubject(params).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.data)
              this.dialogVisible = false
              this.search()
            } else {
              this.$message.warning(res.data)
              this.dialogVisible = false
            }
          })
          // .catch((error) => {})

          // this.getInit();
        }
      })
    },
    // 一级下拉框
    selectChange(e) {
      console.log(e, '---')
      this.current = e
    },
    // 弹窗取消
    resetForm(ruleForm) {
      this.$refs['ruleForm'].resetFields()
      this.dialogVisible = false
    },
    // 关闭弹窗
    handleClose() {
      this.resetForm(this.ruleForm)
    },
    // 重置
    resetBtn() {
      this.tableData = []
      this.value = ''
      this.dataId = ''
      this.searchCurrent = ''
      this.getMonth()
      // this.$refs.tree.setCheckedKeys([data.id], true)
    },
    // 实现单选子级节点
    handleCheckChange(data, checked) {
      console.log(data, checked)
      // 子级只能单选
      if (checked) {
        this.data.id = data.id
        this.dataId = data.label
        this.$refs.tree.setCheckedKeys([data.id], true)
      } else {
        this.data.id = null
      }
    },
    // 选中节点
    handleNodeClick(data) {
      this.data.id = data.id
      this.$refs.tree.setCheckedKeys([data.id], true)
      this.dataId = data.label
    },
    // /表格合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 表格合并行
      // if (columnIndex == 0 || columnIndex == 1) {
      if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.box {
  padding: 20px;
  min-height: calc(90vh - 70px);
  background-color: white;
  display: flex;
  justify-content: flex-start;
  flex-flow: column;
}

.left {
  width: 20%;
  display: flex;
  background-color: white;
  flex-flow: column;
  justify-content: flex-start;
  align-items: center;
  border: 1px solid #ccc;
  border-radius: 4px;
  height: 800px;
}

.right {
  // display: flex;
  // flex-flow: column;
  width: 79%;
  height: 100%;
  padding: 30px 24px;
  margin-left: 24px;
  // border: 1px solid #ccc;
  // height: 800px;
}

.flex-bottom {
  display: flex;
  justify-content: space-between;
}

.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-row {
  width: 100%;
  margin-bottom: 8px;
  align-items: flex-start;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.el-button {
  border-radius: 21px;
  padding: 10px 20px;
  font-size: 16px;
}

.el-button--primary {
  background-color: #2087d0;
}
.el-button--primary:hover {
  background-color: #2087d0cc !important;
}

.el-button--default {
  border-color: #b4b4b4;
  color: #666666;
}

::v-deep .el-input__inner {
  border: 1px solid #b4b4b4;
  font-size: 18px;
  color: #333333;
}

.left-tree {
  width: 85%;
  // height: 343px;
  margin-top: 24px;
  box-shadow: 0px 0px 8px 0px rgba(113, 121, 144, 0.12);
  border-radius: 4px;
  padding: 30px;
}

.just-bet {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

::v-deep .el-table th {
  background-color: #ebecee;
  color: #666666;
  height: 64px;
  font-size: 18px;
  font-weight: 400;
}

::v-deep .el-table tr {
  color: #333333;
  font-size: 18px;
  font-weight: 400;
}

::v-deep .el-tree-node {
  .is-leaf + .el-checkbox .el-checkbox__inner {
    display: inline-block;
  }

  .el-checkbox .el-checkbox__inner {
    display: none;
  }
}

::v-deep .el-form-item__label {
  font-size: 18px;
  color: #666666;
  font-weight: 400;
}

// ::v-deep .el-input.is-disabled .el-input__inner{
//   color: #333333;
// }
::v-deep .el-tree-node__label {
  font-size: 18px;
}

::v-deep .el-tree-node__content {
  margin-bottom: 10px;
}

::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #2087d0;
  border-color: #2087d0;
}

::v-deep .el-checkbox__inner::after {
  border-width: 2px;
}
</style>
